layui.use(['form','treeSelect','layer','upload','laydate','layedit','tableSelect'],function(){
    var form = layui.form
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;
    var upload = layui.upload;
    var laydate = layui.laydate;
    var treeSelect= layui.treeSelect;//树形下拉框
    var imgURL="";//多图片上传的路径

    //选择商家的下拉表格
    var tableSelect = layui.tableSelect;
    tableSelect.render({
        elem: '#merchantName',	//定义输入框input对象 必填
        checkedKey: 'merchantId', //表格的唯一建值，非常重要，影响到选中状态 必填
        searchKey: 'keyword',	//搜索输入框的name值 默认keyword
        searchPlaceholder: '商家名搜索',	//搜索输入框的提示文字 默认关键词搜索
        table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
            url:'/merchant/page',
            page : true,
            height : "full-125",
            limits : [10,15,20,25],
            limit : 10,
            cols: [[
                {type: 'radio'},
                {field: 'merchantId', title: '商家ID', minWidth:100, align:"center"},
                {field: 'merchantName', title: '商家名字', minWidth:100, align:"center"},
                {field: 'contactPhone', title: '联系电话', minWidth:200, align:'center'},

            ]],
        },
        done: function (elem, data) {//点击选择后发生的操作
            //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
            //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
            $("#merchantId").val(data.data[0].merchantId);
            $("#merchantName").val(data.data[0].merchantName);
        }
    })


    var produceDesc;
    //富文本编辑器
    layui.use('layedit', function(){
        var layedit = layui.layedit;
        layedit.set({
            uploadImage: {
                url: '/upload/editPicUpload' //接口url
                ,type: 'post' //默认post
            }

        });
        produceDesc=layedit.build('produceDesc',{
            height: 160 //设置编辑器高度
        }); //建立编辑器

    });

    //回显数据
    var request = GetRequest();
    $.get("/agriecomProduce/" + request.id,function (data) {
        data=data.data.produce;

        $("#produceId").val(data.produceId);
        $("#produceName").val(data.produceName);
        $("#produceBrief").text(data.produceBrief);
        $("#produceParameter").text(data.produceParameter);
        $("#producingArea").text(data.producingArea);
        $("#produceDesc").text(data.produceDesc);
        produceDesc=layui.layedit.build('produceDesc',{
            height: 160 //设置编辑器高度
        });


        $("#produceImg").val(data.produceImg);
        imgURL=data.produceImg;
        var imgURLs = imgURL.split(',');
        for(var j=0,len=imgURLs.length-1;j<len;j++)
        $('#demo2').append('<img width="100" height="100" src="'+ imgURLs[j] +'"  class="layui-upload-img" id="'+ imgURLs[j]+'">');

      //  $("#produceVideo").val(data.produceVideo);
        $("#isHot").val(data.isHot);
        $("#price").val(data.price);
        $("#unit").val(data.unit);
        $("#stock").val(data.stock);
        $("#sourceCode").val(data.sourceCode);
        $("#remarks").val(data.remarks);
        $("#merchantId").val(data.merchantId);
        $.ajax({
            //根据parentId查对应类别，从而拿到父类结点的名称
            url: '/merchant/'+data.merchantId,
            type: 'GET',
            success: function (da) {
                if(da!=null) {
                    $("#merchantName").val(da.merchantName);
                }
            }})


        $.ajax({
            //根据parentId查对应类别，从而拿到父类结点的名称
            url: '/produceCategory/'+data.categoryId,
            type: 'GET',
            success: function (da) {
                if(da!=null) {
                        //渲染菜单的数据到表单元素
                        treeSelect.render({
                            elem: '#tree-select',
                            data: '/produceCategory/treelist',
                            type: 'get',
                            placeholder: da.name,// 占位符
                            search: true,// 是否开启搜索功能：true/false，默认false
                            click: function(d){
                                $("#tree-select").val(d.current.id);
                            },
                            success: function () { // 加载完成后的回调函数
                                $("#tree-select").val(da.id);
                            }
                        });

                }

            }})


        $('#demo2').find('img').each((index,ele)=>{
            $(ele).on('dblclick',()=>{
            //移除图片相应删除掉之前赋给pic的值
            var url=$(ele).attr('src');
        imgURL = imgURL.replace(url+",","");
        $(".pic").val(imgURL);
        $(ele).remove();
        layer.msg("图片已移除");
        });
    });

    });




    //多图片上传
    upload.render({
        elem: '#multiPicBtn',
        field:'uploadFile',
        url: '/upload/pic',
        multiple: true,
        before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#demo2').append('<img width="100" height="100" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" id="'+index+'">');
            });
        },
        done: function(res, index, upload){

            if (res.code === 0) {
                layer.msg(res.msg);
                $("#"+index).attr("src",res.url);
                imgURL+=res.url+",";

                $(".pic").val(imgURL);
            } else {
                layer.msg(res.msg);
            }
        }
    });

    form.on("submit(edit)",function(data){
        //弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        $.post("/agriecomProduce/edit",{
            produceId: $("#produceId").val(),
            produceName: $("#produceName").val(),
            produceBrief: $("#produceBrief").val(),
            price : $("#price").val(),
            unit: $("#unit").val(),
            stock :  $("#stock").val(),
            sourceCode:  $("#sourceCode").val(),
            merchantId:  $("#merchantId").val(),
            categoryId :  $("#tree-select").val(),
            isHot: $("#isHot").val(),
            remarks :  $("#remarks").val(),
            produceParameter: $("#produceParameter").val(),
            producingArea : $("#producingArea").val(),
            produceDesc:  layui.layedit.getContent(produceDesc),
            produceImg : $("#produceImg").val(),
            //  : $(".produceVideo").val(),

        },function(res){

        })
        setTimeout(function(){
            top.layer.close(index);
            top.layer.msg("用户添加成功！");
            layer.closeAll("iframe");
            //刷新父页面
            parent.location.reload();
        },2000);
        return false;
    })


    //获取路径中的参数
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }


});